package top.cyuw.simplerpc.serialize.hessian;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import top.cyuw.simplerpc.exception.SerializeException;
import top.cyuw.simplerpc.serialize.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author chen
 * @date 2023/3/12 21:44
 */
public class HessianSerializer implements Serializer {

    @Override
    public byte[] serialize(Object obj) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            HessianOutput output = new HessianOutput(out);
            output.writeObject(obj);
            return out.toByteArray();
        } catch (Exception e) {
            throw new SerializeException("serialize failed: " + e.getMessage(), e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
            HessianInput input = new HessianInput(in);
            Object obj = input.readObject();
            return clazz.cast(obj);
        } catch (Exception e) {
            throw new SerializeException("deserialize failed: " + e.getMessage(), e);
        }
    }

}
